package com.example.furniture.controller;

import com.example.furniture.entity.Furniture;
import com.example.furniture.service.FurnitureService;
import jakarta.validation.Valid;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URI;
import java.util.List;

/**
 * 家具管理控制器
 * 提供家具的增删改查功能
 * 
 * @author 家具商城系统
 * @version 1.0
 * @since 2024-01-01
 */
@RestController
@RequestMapping("/furniture")
@CrossOrigin(origins = "*") // 允许跨域访问，用于前端调用
public class FurnitureController {

    private static final Logger logger = LoggerFactory.getLogger(FurnitureController.class);
    private final FurnitureService furnitureService;

    /**
     * 构造函数，注入家具服务
     * 
     * @param furnitureService 家具服务实例
     */
    public FurnitureController(FurnitureService furnitureService) {
        this.furnitureService = furnitureService;
    }

    /**
     * 获取所有家具列表
     * 
     * @return 家具列表
     */
    @GetMapping
    public ResponseEntity<List<Furniture>> list() {
        try {
            logger.info("获取所有家具列表");
            List<Furniture> furniture = furnitureService.listAll();
            logger.info("成功获取家具列表，共{}条记录", furniture.size());
            return ResponseEntity.ok(furniture);
        } catch (Exception e) {
            logger.error("获取家具列表失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * 根据ID获取家具信息
     * 
     * @param id 家具ID
     * @return 家具信息，如果不存在返回404
     */
    @GetMapping("/{id}")
    public ResponseEntity<Furniture> get(@PathVariable("id") Long id) {
        try {
            logger.info("获取家具信息，ID: {}", id);
            Furniture furniture = furnitureService.getById(id);
            if (furniture == null) {
                logger.warn("家具不存在，ID: {}", id);
                return ResponseEntity.notFound().build();
            }
            return ResponseEntity.ok(furniture);
        } catch (Exception e) {
            logger.error("获取家具信息失败，ID: {}", id, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * 创建新家具
     * 
     * @param furniture 家具信息
     * @return 创建的家具信息
     */
    @PostMapping
    public ResponseEntity<Furniture> create(@Valid @RequestBody Furniture furniture) {
        try {
            logger.info("创建新家具: {}", furniture.getName());
            Furniture saved = furnitureService.create(furniture);
            logger.info("家具创建成功，ID: {}, 名称: {}", saved.getId(), saved.getName());
            return ResponseEntity.created(URI.create("/furniture/" + saved.getId())).body(saved);
        } catch (Exception e) {
            logger.error("创建家具失败: {}", furniture.getName(), e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * 更新家具信息
     * 
     * @param id 家具ID
     * @param furniture 更新的家具信息
     * @return 更新后的家具信息
     */
    @PutMapping("/{id}")
    public ResponseEntity<Furniture> update(@PathVariable("id") Long id, @Valid @RequestBody Furniture furniture) {
        try {
            logger.info("更新家具信息，ID: {}", id);
            Furniture existingFurniture = furnitureService.getById(id);
            if (existingFurniture == null) {
                logger.warn("家具不存在，无法更新，ID: {}", id);
                return ResponseEntity.notFound().build();
            }
            Furniture updated = furnitureService.update(id, furniture);
            logger.info("家具更新成功，ID: {}, 名称: {}", id, updated.getName());
            return ResponseEntity.ok(updated);
        } catch (Exception e) {
            logger.error("更新家具失败，ID: {}", id, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * 删除家具
     * 
     * @param id 家具ID
     * @return 删除结果
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> delete(@PathVariable("id") Long id) {
        try {
            logger.info("删除家具，ID: {}", id);
            Furniture existingFurniture = furnitureService.getById(id);
            if (existingFurniture == null) {
                logger.warn("家具不存在，无法删除，ID: {}", id);
                return ResponseEntity.notFound().build();
            }
            furnitureService.delete(id);
            logger.info("家具删除成功，ID: {}", id);
            return ResponseEntity.noContent().build();
        } catch (Exception e) {
            logger.error("删除家具失败，ID: {}", id, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
}


